import 'dart:math' as math;

import 'package:wechat_assets_picker/wechat_assets_picker.dart';
import 'package:wechat_camera_picker/wechat_camera_picker.dart';

import '../index.dart';

typedef SelectPhoto = void Function(List<TyPhoto> value);

class TyPhoto {
  late String? url;
  late AssetEntity? file;

  String? thumbnail() {
    if (url != null) {
      // http://10.98.119.196:9000/gxsaas-edison/XFILE/2022-05-11/aa7f5075-9274-4960-bf05-ea9e136b1b45.jpg
      Debug.info("原图地址：$url");
      String thumbnailUrl =
          url!.substring(url!.indexOf("gxsaas-edison"));
      if(url!.contains("oss.saas.sit.guoxintianyu.com")){
        //sit
        thumbnailUrl = "http://thumb.saas.sit.guoxintianyu.com/gxty/resize:fit:200:200/plain/s3://$thumbnailUrl";
      } else if(url!.contains("oss.saas.uat.guoxintianyu.com")){
        //uat
        thumbnailUrl = "http://thumb.saas.uat.guoxintianyu.com/gxty/resize:fit:200:200/plain/s3://$thumbnailUrl";
      } else if(url!.contains("oss.saas.pro.guoxintianyu.com")){
        //pro
        thumbnailUrl = "http://thumb.saas.pro.guoxintianyu.com/gxty/resize:fit:200:200/plain/s3://$thumbnailUrl";
      } else {
        return url;
      }
      Debug.info("缩略图地址：$thumbnailUrl");
      return thumbnailUrl;
    } else {
      return null;
    }
  }

  TyPhoto({this.url, this.file});
}

class CommonPhotoSelect extends BaseUpDownWidget {
  /*相片列表*/
  final List<TyPhoto> photos;

  /*最大值*/
  final int max;

  /*只能拍照*/
  final bool onlyShoot;

  CommonPhotoSelect(
      {Key? key,
      required this.photos,
      this.max = 9,
      this.onlyShoot = false,
      required title,
      isHideDivide = false,
      isRequired = false})
      : super(
            key: key,
            title: title,
            isHideDivide: isHideDivide,
            isRequired: isRequired);

  // final ImagePicker _picker = ImagePicker();

  @override
  Widget build(BuildContext context) {
    setDownWidget(
      _PhotoWidget(
        photos: photos,
        max: max,
        onlyShoot: onlyShoot,
      ),
    );
    return super.build(context);
  }
}

class _PhotoWidget extends StatefulWidget {
  /*相片列表*/
  final List<TyPhoto> photos;

  /*最大值*/
  final int max;

  /*只能拍照*/
  final bool onlyShoot;

  _PhotoWidget({
    Key? key,
    required this.photos,
    this.max = 9,
    this.onlyShoot = false,
  }) : super(key: key);

  @override
  _PhotoState createState() => _PhotoState();
}

class _PhotoState extends State<_PhotoWidget> {
  /*每行数量*/
  static const int kRowNum = 4;

  @override
  Widget build(BuildContext context) {
    int length = widget.photos.length + 1;
    if (widget.max > 0) {
      length = math.min(length, widget.max);
    }
    double width = 76.67;
    double margin = 16;

    double allWidth = MediaQuery.of(context).size.width - 48;
    if (kRowNum * width + (kRowNum - 1) * margin < allWidth) {
      width = (allWidth - (kRowNum - 1) * margin) / kRowNum;
    } else {
      margin = (allWidth - kRowNum * width) / (kRowNum - 1);
    }

    int column = (length / kRowNum).ceil();
    List<Widget> columnList = [];
    if (widget.max == 0) {
      columnList.add(
        Padding(
          padding: const EdgeInsets.only(bottom: 10),
          child: Text(
            "建议单个图片不超过20M。",
            textAlign: TextAlign.start,
            style: Theme.of(context).textTheme.labelMedium?.copyWith(
                  color: Theme.of(context).colorScheme.onSecondary,
                ),
          ),
        ),
      );
    } else {
      columnList.add(
        Padding(
          padding: const EdgeInsets.only(bottom: 10),
          child: Text(
            "最多${widget.max}张，建议单个图片不超过20M。",
            textAlign: TextAlign.start,
            style: Theme.of(context).textTheme.labelMedium?.copyWith(
                  color: Theme.of(context).colorScheme.onSecondary,
                ),
          ),
        ),
      );
    }

    for (int i = 0; i < column; i++) {
      List<Widget> rowList = [];
      if (i > 0) {
        columnList.add(const SizedBox(
          height: 16,
        ));
      }
      for (int j = 0; j < kRowNum; j++) {
        int index = i * kRowNum + j;
        if (j > 0) {
          rowList.add(SizedBox(
            width: margin,
          ));
        }
        if (index < widget.photos.length) {
          TyPhoto photo = widget.photos[index];
          ImageProvider imageProvider;
          if (photo.file != null) {
            // imageProvider = FileImage(
            //   File(photo.file!.relativePath),
            // );
            imageProvider =
                AssetEntityImageProvider(photo.file!, isOriginal: false);
          } else {
            imageProvider = NetworkImage(photo.url!);
          }
          rowList.add(Stack(
            children: [
              Positioned(
                child: InkWell(
                  child: Container(
                    width: width,
                    height: width,
                    decoration: ShapeDecoration(
                        image: DecorationImage(
                            image: imageProvider, fit: BoxFit.cover),
                        shape: RoundedRectangleBorder(
                            borderRadius:
                                BorderRadiusDirectional.circular(3.33))),
                  ),
                  onTap: () {
                    //点击事件
                    previewPhoto(context, index);
                  },
                ),
              ),
              Positioned(
                  top: -10,
                  right: -10,
                  child: IconButton(
                    icon: Icon(
                      Icons.remove_circle_outline,
                      color: Theme.of(context).colorScheme.onSecondary,
                    ),
                    onPressed: () {
                      setState(() {
                        widget.photos.remove(photo);
                      });
                    },
                  ))
            ],
          ));
        } else if (index == widget.photos.length) {
          rowList.add(
            InkWell(
              child: Container(
                width: width,
                height: width,
                decoration: ShapeDecoration(
                    image: const DecorationImage(
                        image: AssetImage("images/common_photo.png"),
                        fit: BoxFit.cover),
                    shape: RoundedRectangleBorder(
                        borderRadius: BorderRadiusDirectional.circular(3.33))),
              ),
              onTap: () {
                //点击事件
                addPhoto(context);
              },
            ),
          );
        }
      }
      columnList.add(Row(
        children: rowList,
      ));
    }
    return Column(
      children: columnList,
      crossAxisAlignment: CrossAxisAlignment.start,
    );
  }

  void previewPhoto(BuildContext context, int index) {
    Navigator.of(context).push(MaterialPageRoute(
        builder: (context) => PreviewPhotoPage(
              photos: widget.photos,
              index: index,
            )));
  }

  Future<void> addPhoto(BuildContext context) async {
    if (widget.onlyShoot) {
      final AssetEntity? entity = await CameraPicker.pickFromCamera(context);

      if (entity != null) {
        setState(() {
          widget.photos.add(TyPhoto(file: entity));
        });
      }
    } else {
      //选择照片
      showModalBottomSheet(
        context: context,
        builder: (BuildContext context) {
          return SafeArea(
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: <Widget>[
                ListTile(
                  leading: Icon(Icons.photo_camera),
                  title: Text("拍照"),
                  onTap: () async {
                    Navigator.pop(context);
                    final AssetEntity? entity =
                        await CameraPicker.pickFromCamera(context);
                    // ,pickerConfig: const CameraPickerConfig(
                    //     resolutionPreset: ResolutionPreset.ultraHigh));
                    Debug.info("${entity?.relativePath.toString()}");
                    if (entity != null) {
                      setState(() {
                        widget.photos.add(TyPhoto(file: entity));
                      });
                    }
                  },
                ),
                ListTile(
                  leading: Icon(Icons.photo_library),
                  title: Text("相册"),
                  onTap: () async {
                    Navigator.pop(context);
                    List<AssetEntity> list = [];
                    int netPhotoNum = 0;
                    for (var o in widget.photos) {
                      if (o.file != null) {
                        list.add(o.file!);
                      } else {
                        netPhotoNum++;
                      }
                    }

                    final List<AssetEntity>? result =
                        await AssetPicker.pickAssets(context,
                            pickerConfig: AssetPickerConfig(
                                maxAssets: widget.max == 0
                                    ? 99
                                    : widget.max - netPhotoNum,
                                selectedAssets: list));
                    setState(() {
                      for (int i = widget.photos.length - 1; i >= 0; i--) {
                        TyPhoto photo = widget.photos[i];
                        if (photo.file != null) {
                          widget.photos.remove(photo);
                        }
                      }
                      if (result != null) {
                        for (AssetEntity asset in result) {
                          widget.photos.add(TyPhoto(file: asset));
                        }
                      }
                    });
                  },
                ),
              ],
            ),
          );
        },
      );
    }
  }
}

class CommonPhotoWidget extends BaseUpDownWidget {
  /*每行数量*/
  static const int kRowNum = 4;

  // /*相片列表*/
  late List<TyPhoto> photos = [];

  /*相片列表*/
  final String photoStr;

  CommonPhotoWidget(
      {Key? key, required this.photoStr, required title, isHideDivide = false})
      : super(
            key: key,
            title: title,
            isHideDivide: isHideDivide,
            isRequired: false);

  @override
  Widget build(BuildContext context) {
    photos.clear();
    var list = photoStr.split(",");
    for (var o in list) {
      if (o.isNotEmpty) {
        photos.add(TyPhoto(url: o));
      }
    }

    int length = photos.length;

    double width = 76.67;
    double margin = 16;
    double allWidth = MediaQuery.of(context).size.width - 48;
    if (kRowNum * width + (kRowNum - 1) * margin < allWidth) {
      width = (allWidth - (kRowNum - 1) * margin) / kRowNum;
    } else {
      margin = (allWidth - kRowNum * width) / (kRowNum - 1);
    }
    int column = (length / kRowNum).ceil();
    List<Widget> columnList = [];
    for (int i = 0; i < column; i++) {
      List<Widget> rowList = [];
      if (i > 0) {
        columnList.add(const SizedBox(
          height: 16,
        ));
      }
      for (int j = 0; j < kRowNum; j++) {
        int index = i * kRowNum + j;
        if (j > 0) {
          rowList.add(SizedBox(
            width: margin,
          ));
        }
        if (index < photos.length) {
          TyPhoto photo = photos[index];
          rowList.add(
            InkWell(
              child: Container(
                width: width,
                height: width,
                decoration: ShapeDecoration(
                    image: DecorationImage(
                        image: NetworkImage(photo.thumbnail()!),
                        fit: BoxFit.cover),
                    shape: RoundedRectangleBorder(
                        borderRadius: BorderRadiusDirectional.circular(3.33))),
              ),
              onTap: () {
                //点击事件
                previewPhoto(context, index);
              },
            ),
          );
        }
      }
      columnList.add(Row(
        children: rowList,
      ));
    }

    setDownWidget(
      Column(
        children: columnList,
      ),
    );
    return super.build(context);
  }

  void previewPhoto(BuildContext context, int index) {
    Navigator.of(context).push(MaterialPageRoute(
        builder: (context) => PreviewPhotoPage(
              photos: photos,
              index: index,
            )));
  }
}
